package com.adds.lvds.controller.organize;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.adds.lvds.core.utils.CommUtils;
import com.adds.lvds.model.organize.SysOrgInfo;
import com.adds.lvds.model.organize.SysOrgUser;
import com.adds.lvds.model.organize.SysUserInfo;
import com.adds.lvds.security.acegi.utils.CurrentUserUtils;
import com.adds.lvds.security.model.SysCurrentUser;
import com.adds.lvds.service.impl.organize.OrganizeInfoService;
import com.adds.lvds.service.impl.organize.OrganizeTreeService;
import com.adds.lvds.service.impl.organize.SysUserInfoService;

@Controller
@RequestMapping("/organize/")
public class SysOrganizeInfoController {
	@Inject
	private OrganizeInfoService organizeInfoService;

	@Inject
	private SysUserInfoService sysUserInfoService;
	@Inject
	private OrganizeTreeService organizeTreeService;

	@RequestMapping("sys_organize_list")
	public String sys_org_list() {
		return "/organize/sys_organize_list";
	}

	/**
	 * 首页初始化
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="execute")
	public List<Object> execute(HttpServletRequest request, HttpServletResponse response)
			throws Exception {// 4个格式
		String Org_id = request.getParameter("id");
		SysCurrentUser sysCurrentUser = CurrentUserUtils.currentUser(request);
		boolean initFlag = false;
		if (StringUtils.isEmpty(Org_id)) {
			initFlag = true;
			if("admin".equals(sysCurrentUser.getUserName())){
				Org_id = "1";
			}else{
				if(sysCurrentUser.getSysUserPermission()!= null){
					Org_id = String.valueOf(sysCurrentUser.getSysUserPermission().getOrg_id());
				}
			}
		
		}
		List<Object> list = organizeTreeService.getOrgJson(String.valueOf(sysCurrentUser.getId()), Org_id, initFlag);
		return list;
	}

	/**
	 * 根据部门查询该部门的位置
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("getDepartment")
	public void getDepartment(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object> treeList = new ArrayList<Object>();
		String empName = request.getParameter("name");
		map.clear();
		map.put("org_name", empName);
		SysOrgInfo sysOrgInfo = organizeInfoService.findSysOrgInfoByMap(map);
		if (sysOrgInfo != null && !"".equals(sysOrgInfo)) {
			String id = String.valueOf(sysOrgInfo.getOrg_id());// 这是父节点的Id
			JSONObject object = getDeptName(id);
			treeList.add(object);
		}
		JSONArray json = JSONArray.fromObject(treeList);
		request.setCharacterEncoding("UTF-8"); // 这里不设置编码会有乱码
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(json.toString());
		writer.flush();
		writer.close();
	}

	/**
	 * 查询该id的位置
	 * 
	 * @param id
	 * @return
	 */
	public JSONObject getDeptName(String id) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.clear();
		model.put("org_id", id);
		SysOrgInfo lists = organizeInfoService.findSysOrgInfoByMap(model);// 根据名称查询到的部门:1
		String parentOrgID = String.valueOf(lists.getParent_org_id());
		// model.clear();
		// model.put("parentOrgID", parentOrgID);
		// List<OrganizeInfoVo> list =
		// organizeInfoService.findOrganizeInfoVoByMap(model);//该部门的同级部门:n
		// 获取到该部门与其评级部门，还要加员工
		model.clear();
		model.put("org_id", parentOrgID);
		SysOrgInfo pList = organizeInfoService.findSysOrgInfoByMap(model);// 该部门的父部门:1
		JSONObject objectFa = new JSONObject();// 父节点object
		objectFa.put("id", pList.getOrg_id());
		objectFa.put("name", pList.getOrg_name());
		objectFa.put("pId", pList.getParent_org_id());
		objectFa.put("isParent", true);
		objectFa.put("open", true);
		List<Object> sunList = new ArrayList<Object>();
		JSONObject objectSun = new JSONObject();// 该部门节点
		objectSun.put("id", lists.getOrg_id());
		objectSun.put("name", lists.getOrg_name());
		objectSun.put("pId", lists.getParent_org_id());
		List<Object> userList = new ArrayList<Object>();
		if (lists.getChildOrgs().size() > 0) {
			model.clear();
			model.put("parent_org_id", lists.getOrg_id());
			List<SysOrgInfo> list = organizeInfoService
					.getSysOrgInfoByMap(model);// 该部门的同级部门:n
			if (list.size() > 0) {
				for (SysOrgInfo sysOrgInfo : list) {
					JSONObject userJson = new JSONObject();
					userJson.put("id", sysOrgInfo.getOrg_id());
					userJson.put("name", sysOrgInfo.getOrg_name());
					userJson.put("pId", sysOrgInfo.getParent_org_id());
					if (sysOrgInfo.getChildOrgs().size() > 0) {
						userJson.put("isParent", true);
					}
					userList.add(userJson);
				}
			}
			JSONArray Json = JSONArray.fromObject(userList);
			objectSun.put("children", Json);
		}
		sunList.add(objectSun);
		JSONArray childJson = JSONArray.fromObject(sunList);
		objectFa.put("children", childJson);

		return objectFa;
	}

	// 录入组织数据
	@ResponseBody
	@RequestMapping("insertSysOrgInfo")
	public SysOrgInfo insertSysOrgInfo(@Param(value = "sysOrgInfo")SysOrgInfo sysOrgInfo,
			HttpServletResponse response) {
		return organizeInfoService.insertSysOrgInfo(sysOrgInfo);

	}
	//跳转编辑页面
	@RequestMapping("editOrgMap")
	public String editOrgMap(@Param(value = "org_id")String org_id,Model model){
		SysOrgInfo sysOrgInfo=organizeInfoService.findCurrentOrgAndChildOrgs(org_id);
		model.addAttribute("sysOrgInfo", sysOrgInfo);
		return "/organize/edit_sys_organize";
	}
	
	// 修改组织数据
	@RequestMapping("doEditSysOrg")
	@ResponseBody
	public Map<String,Object> doEditSysOrg(SysOrgInfo sysOrgInfo) {
		Map<String,Object> map=new HashMap<String,Object>();
		//model.put("org_id", org_id);
		//SysOrgInfo sysOrgInfo = organizeInfoService.findSysOrgInfoByMap(model);
		String result = organizeInfoService.updateSysOrgInfo(sysOrgInfo);
		map.put("status", result);
		return map;
	}
	// 修改组织数据
	@ResponseBody
	@RequestMapping("updateSysOrg")
	public String updateSysOrgInfo(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		String org_id = request.getParameter("id");
		String org_name = request.getParameter("name");
		model.put("org_id", org_id);
		SysOrgInfo sysOrgInfo = organizeInfoService.findSysOrgInfoByMap(model);
		sysOrgInfo.setOrg_id(Integer.parseInt(org_id));
		sysOrgInfo.setOrg_name(org_name);
		String result = organizeInfoService.updateSysOrgInfo(sysOrgInfo);
		return result;
	}
    
	// 删除组织数据
	@ResponseBody
	@RequestMapping("deleteSysOrgInfo")
	public String deleteSysOrgInfo(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		String Org_id = request.getParameter("id");
		model.put("org_id", Org_id);
		List<SysOrgUser> list=organizeInfoService.findSysOrgUserByMap(model);
		String result =CommUtils.SUCC;
		if(list!=null&&list.size()>0){
			result=CommUtils.EXIT;
		}else{
			result= organizeInfoService.deleteSysOrgInfo(Org_id);
		}
		
		return result;
	}
	
	// 删除该节点以及所有子节点
	public void findId(String id) {
		organizeInfoService.deleteSysOrgInfo(id);
		List<SysOrgInfo> groups = organizeInfoService.findSysOrgByParentId(id);
		for (SysOrgInfo s : groups) {
			organizeInfoService.deleteSysOrgInfo(String.valueOf(s.getOrg_id()));
			findId(String.valueOf(s.getOrg_id()));
		}
	}

	/**
	 * 导出
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("exportOrg")
	public void exportOrg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// String parent_org_id,
		try {
			String parent_org_id = request.getParameter("parent_org_id");
			// String org_id = "1";
			// // 声明一个工作薄
			HSSFWorkbook wb = new HSSFWorkbook();
			// 声明一个单子并命名
			HSSFSheet sheet = wb.createSheet("组织机构");
			// 创建第一(0)行（也可以称为表头）
			int row_v = sheet.getPhysicalNumberOfRows();
			HSSFRow row = sheet.createRow(row_v);// 第0行 rowNum=0
			// 表格第0行赋值
			row.createCell(0).setCellValue("人员编码");// 第0列，输入字符串"人员编码"
			row.createCell(1).setCellValue("姓名");// 第1列，输入字符串"人员编码"
			row.createCell(2).setCellValue("手机号码");// 第2列，输入字符串"手机号码"
			row.createCell(3).setCellValue("短号");// 第3列，输入字符串"短号"
			row.createCell(4).setCellValue("性别");
			row.createCell(5).setCellValue("邮箱地址");
			row.createCell(6).setCellValue("出生日期");
			row.createCell(7).setCellValue("籍贯");
			row.createCell(8).setCellValue("专业技术资格名称");
			row.createCell(9).setCellValue("身份证号");
			row.createCell(10).setCellValue("岗位");
			row.createCell(11).setCellValue("所属部门");
			SysOrgInfo sys_org = null;
			if (!"0".endsWith(parent_org_id)) {
				Map<String, Object> map = new HashMap<>();
				map.put("parent_org_id", parent_org_id);
				// 根据这个父Id查询这个父id的所有信息
				sys_org = organizeInfoService.findSysOrgInfoByMap(map);
				this.writerOrgInfo(sheet, row, parent_org_id,
						sys_org.getOrg_name(), sys_org.getRemark());
			} else {
				List<SysOrgInfo> sysOrg = this.organizeInfoService
						.findSysOrgByParentId(parent_org_id);
				for (SysOrgInfo sysOrgInfo : sysOrg) {
					this.writerOrgInfo(sheet, row,
							String.valueOf(sysOrgInfo.getOrg_id()),
							sysOrgInfo.getOrg_name(), sysOrgInfo.getRemark());
				}
			}
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String("组织机构信息.xls".getBytes(), "iso-8859-1"));
			OutputStream out = response.getOutputStream();
			wb.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 输出组织机构信息
	private void writerOrgInfo(HSSFSheet sheet, HSSFRow row,
			String parent_org_id, String orgName, String area) {
		Map<String, Object> map = new HashMap<>();
		map.put("parent_org_id", parent_org_id);
		// 根据这个父Id查询这个父id的所有信息
		SysOrgInfo sys_org = organizeInfoService.findSysOrgInfoByMap(map);
		try {
			if (sys_org != null) {
				for (int i = 0; i < sys_org.getUserInfos().size(); i++) {
					SysUserInfo userInfo = sys_org.getUserInfos().get(i);
					int row_v = sheet.getPhysicalNumberOfRows();
					row = sheet.createRow(row_v);
					// 行 列 字符
					row.createCell(0).setCellValue(userInfo.getEmp_id());
					row.createCell(1).setCellValue(userInfo.getEmp_name());
					row.createCell(2).setCellValue(userInfo.getMobile_phone());
					String sex_Name = "男";
					if (userInfo.getSex() == 1) {
						sex_Name = "男";
					} else {
						sex_Name = "女";
					}
					row.createCell(3).setCellValue(sex_Name);
					row.createCell(4).setCellValue(userInfo.getEmail());
					row.createCell(5).setCellValue(userInfo.getPosition());
					row.createCell(6).setCellValue(userInfo.getProfessional());
					row.createCell(7).setCellValue(orgName);
				}
				List<SysOrgInfo> orgInfos = sys_org.getChildOrgs();
				for (SysOrgInfo sysOrgInfo : orgInfos) {
					this.writerOrgInfo(sheet, row,
							String.valueOf(sysOrgInfo.getOrg_id()), orgName
									+ "-" + sysOrgInfo.getOrg_name(),
							sysOrgInfo.getRemark());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("inputOrg")
	public void inputOrg(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// HSSFWorkbook hwb, int destOrgID
		String org_id = request.getParameter("insert_org_id");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipart = multipartRequest.getFile("file");
		// InputStream multipart = new FileInputStream("file.xls");
		HSSFWorkbook hwb = new HSSFWorkbook(multipart.getInputStream());
		// Map<String, Object> condition = new HashMap<String, Object>();
		SysUserInfo userInfo = null;
		// 创建Excel工作簿
		HSSFSheet sheet = hwb.getSheetAt(0);
		HSSFRow row = null;
		try {
			for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {

				row = sheet.getRow(i);
				userInfo = new SysUserInfo();// 直接接收转换SysUserInfo实体类格式，不能这样直接接收
				String emp_id = row.getCell(0).toString();// String
				String emp_name = row.getCell(1).toString();// String
				String mobile_phone = row.getCell(2).toString();// String
				String sexName = row.getCell(3).toString();// 0||1
				String email = row.getCell(4).toString();// String
				String position = row.getCell(5).toString();// 籍贯String
				String professional = row.getCell(6).toString();// 专业String
				userInfo.setEmp_id(emp_id);
				userInfo.setEmp_name(emp_name);
				userInfo.setMobile_phone(mobile_phone);
				if (sexName == "男") {
					userInfo.setSex(1);//
				} else {
					userInfo.setSex(0);
				}
				userInfo.setEmail(email);
				userInfo.setProfessional(professional);
				userInfo.setPosition(position);

				SysOrgUser sysOrgUser = new SysOrgUser();// new一个实体类
				String orgName = row.getCell(11).toString();// 部门名称：需要遍历
				String destOrgID = org_id;// 父id 将数据导入该部门下面

				String orgId = getOrgId(orgName, destOrgID);
				// 传输一个map空壳,和部门所需的两个值，并完成部门的建立,再返回一个该人员的所在部门id【2】

				sysOrgUser.setEmp_id(emp_id);
				sysOrgUser.setOrg_id(orgId);
				sysUserInfoService.addUserInfo(userInfo, sysOrgUser);// 添加人员信息：可获取emp_id/【1】
				// organizeInfoService.insertSysOrgUser(sysOrgUser);//
				// 建立人员信息与部门的关联【3】

			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 根据部门名称获取部门ID
	private String getOrgId(String orgName, String destOrgID) {
		// 传输一个map空壳,和部门所需的两个值，并完成部门的建立,再返回一个该人员的所在部门id【2】
		String orgId = null;// 返回值
		// 按照'-'进行部门结构信息截取
		String[] orgNames = orgName.split("-");
		for (int i = 0; i < orgNames.length; i++) {
			if (orgNames[i].trim().equals("")) {
				continue;
			}
			orgId = this.getOrgInfo(destOrgID, orgNames[i]);// 查询是否存在-->
			// 如果部门不存在则新建一个部门
			if (orgId == "-1") {// 干掉
				SysOrgInfo organizeInfo = new SysOrgInfo();
				organizeInfo.setOrg_name(orgNames[i]);// name
				organizeInfo.setParent_org_id(Integer.parseInt(destOrgID));// 已完善，父id
				Map<String, Object> map = new HashMap<>();
				map.put("org_id", destOrgID);
				// 根据这个父Id查询这个父id的所有信息
				String Parent_org_name = organizeInfoService
						.findSysOrgInfoByMap(map).getOrg_name();
				organizeInfo.setParent_name(Parent_org_name);// 已完善,父name
				this.organizeInfoService.insertSysOrgInfo(organizeInfo);// 建立部门
				orgId = String.valueOf(organizeInfo.getOrg_id());// 获取建立的部门的id
			}
			destOrgID = orgId;// 给全剧变量destOrgID赋新值
		}
		return orgId;
	}

	// 从数据库中按照部门名字查询部门信息
	private String getOrgInfo(String orgID, String orgName) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("org_name", orgName);
		condition.put("parent_org_id", orgID);
		List<SysOrgInfo> orgInfolist = this.organizeInfoService
				.getSysOrgInfoByMap(condition);// "getSysOrgInfoByMap"
		if (orgInfolist.isEmpty()) {
			return "-1";
		}
		return String.valueOf(orgInfolist.get(0).getOrg_id());
	}
	
	@RequestMapping("toMap")
	public String toMap(){
		
		return "/organize/map_organize_point";
	}
}
